package com.component;

import com.Listener.ActionDoneListener;
import com.dao.DeleteFarmer;
import com.dao.DeleteProductCategory;
import com.dao.DeleteUser;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class ProductCategoryManageComponent extends Box {
    final int WIDTH=1000;
    final int HEIGHT=600;

    JFrame jf = null;
    private JTable table;
    private JTableHeader jth;
    private JScrollPane scrollPane;
    private Object[][] info;

    public ProductCategoryManageComponent(JFrame jf) {
        //垂直布局
        super(BoxLayout.Y_AXIS);
        //组装视图
        this.jf = jf;

        scrollPane = new JScrollPane();
        JPanel btnPanel = new JPanel();
        Color color = new Color(203, 220, 217);
        btnPanel.setBackground(color); //设置背景颜色
        btnPanel.setMaximumSize(new Dimension(WIDTH, 100)); //设置最大宽高
        btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); // 默认的panel是从左侧开始的流式布局，此处设置为从右侧开始布局的流式布局

        JButton addBtn = new JButton("添加");
        JButton updateBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");

        //添加的监听
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹出一个对话框，让用户输入农产品类别的信息
                new AddProductCategoryDialog(jf, "添加农产品类别", true,new ActionDoneListener(){
                    @Override
                    public void done(Object result) {
                        requestProductCategoryData();
                    }
                }) .setVisible(true);
            }
        });

        //跟新的监听
        updateBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取当前表格选中的id
                int selectedRow = table.getSelectedRow();//如果有选中的条目，则返回条目的行号，如果没有选中，那么返回-1

                if (selectedRow==-1){
                    JOptionPane.showMessageDialog(jf,"请选择要修改的条目！");
                    return;
                }

                String CategoryID = info[selectedRow][0].toString();

                //弹出一个对话框，让用户修改
                new UpdateProductCategoryDialog(jf, "修改农产品类别", true, new ActionDoneListener() {
                    @Override
                    public void done(Object result) {
                        requestProductCategoryData();
                    }
                },CategoryID).setVisible(true);
            }
        });

        //添加删除的监视
        deleteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取选中的条目
                int selectedRow = table.getSelectedRow();//如果有选中的条目，则返回条目的行号，如果没有选中，那么返回-1

                if (selectedRow==-1){
                    JOptionPane.showMessageDialog(jf,"请选择要删除的条目！");
                    return;
                }

                //防止误操作
                int result = JOptionPane.showConfirmDialog(jf, "确认要删除选中的条目吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION){
                    return;
                }

                int categoryID = (int)info[selectedRow][0];

                new DeleteProductCategory().deleteProductCategory(categoryID);
                JOptionPane.showMessageDialog(jf, "删除成功!");
                requestProductCategoryData();
            }
        });

        //组装表格
        btnPanel.add(addBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(deleteBtn);
        this.add(btnPanel); // 将按钮添加进去

        //向数据库请求数据
        requestProductCategoryData();
        //设置只能选中一行
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    }

    //请求数据
    public void requestProductCategoryData() {
        try {
            //加载驱动
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取连接
        String id = "sa";
        String pwd = "123456";
        String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=FarmProductSalesSystem";
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(url,id,pwd);
            String sql = "select * from ProductCategory";
            stat = conn.createStatement(); //用于执行sql语句
            rs = stat.executeQuery(sql); //返回查询后的结果
            int count = 0;
            while(rs.next()){
                count++;
            }
            rs = stat.executeQuery(sql);
            // 将查询获得的记录数据，转换成适合生成JTable的数据形式
            String[] ts = {"农产品类别编号","类别名称","备注"};
            info = new Object[count][3];
            count = 0;
            while(rs.next()){
                info[count][0] = Integer.valueOf(rs.getInt("CategoryID"));
                info[count][1] = rs.getString("CategoryName");
                info[count][2] = rs.getString("Remarks");
                count++;
            }
            this.table = new JTable(info,ts){
                @Override //设置不可编辑
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            //显示表头
            this.jth = this.table.getTableHeader();
            //设置滚动条
            this.scrollPane.getViewport().add(table);
            this.add(scrollPane);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接数据库失败！");
        }finally{
            //关闭coon
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭stat
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭rs
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
